import 'package:flutter/material.dart';

/// 搜索类型组件
class ItemGroup extends StatefulWidget {
  @required
  Function onItemChange;

  @required
  var items = <String>[];

  @required
  ItemGroup({this.onItemChange, this.items})
      : assert(onItemChange != null),
        assert(items != null);

  @override
  _ItemGroup createState() => _ItemGroup();
}

class _ItemGroup extends State<ItemGroup> {
  int _currentIndex = 0;

  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
    });
    widget.onItemChange(widget.items[index]);
  }

  Widget buildItem(String text, int index, BuildContext context) {
    var selecedBoxDecoration = BoxDecoration(
      borderRadius: BorderRadius.circular(16.5),
      color: Colors.white,
      border: Border.all(
        // 设置边框样式
        width: 0.4,
        style: BorderStyle.solid,
      ),
    );

    var selected = index == _currentIndex;
    return GestureDetector(
      onTap: () => {_onTap(index)},
      child: DecoratedBox(
        decoration: selected ? selecedBoxDecoration : BoxDecoration(),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 6),
          child: Text(
            text,
            style: TextStyle(
              color: selected
                  ? Theme.of(context).primaryColor
                  : Theme.of(context).accentColor,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 0,
        vertical: 12,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: widget.items
            .asMap()
            .keys
            .map((i) => buildItem(widget.items[i], i, context))
            .toList(),
      ),
    );
  }
}
